package ivan.cheng.tuqu.view;

import ivan.cheng.tuqu.Globals;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.Html;
import android.text.Html.ImageGetter;
import android.text.Selection;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.widget.EditText;

public class ImageEditText extends EditText {

	public ImageEditText(Context context) {
		super(context);
	}
	public ImageEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
	
	
	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
	}
	
	@Override
	protected void onTextChanged(CharSequence text, int start, int before,
			int after) {
		super.onTextChanged(text, start, before, after);
		
		
	}
	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		switch (keyCode)
	    {
	    case KeyEvent.KEYCODE_DPAD_CENTER:
	    	break;
	    case KeyEvent.KEYCODE_BACK:
	    	break;
	    case KeyEvent.KEYCODE_ENTER:
	    	break;
	    default:
	    	break;
	    }
		return super.onKeyUp(keyCode, event);
		
	}
	@Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
	public void insertIcon(final int id,String sPattern){
		
		
		ImageGetter imageGetter = new ImageGetter() {
			public Drawable getDrawable(String source) {
				//int id = Integer.parseInt(source);
				Drawable d = getResources().getDrawable(id);
				d.setBounds(0, 0, d.getIntrinsicWidth(), d
						.getIntrinsicHeight());
				return d;
			}
		};

     CharSequence cs = Html.fromHtml("<img src='" + sPattern + "'/>",imageGetter, null);
     int ipos = getSelectionStart();
		ipos = getSelectionEnd();
	if(Globals.MAX_INPUT_LENGTH < (GetContentText().length() + sPattern.length()))
	{//超过最大长度了
		return;
	}
     getText().insert(ipos,cs);

     Editable etext = getText(); 
     Selection.setSelection(etext, ipos+cs.length());

	}
	
	public String GetContentText()
	{
		String s = FilterHtml(Html.toHtml(getText()));
		return s.replaceAll("&nbsp", " ").replaceAll("&apos", "'").replaceAll("&quot", "\"").replaceAll("&bmp", "&").replaceAll("&lt", "<").replaceAll("&gt", ">").replaceAll("<br>", "\r\n");
	}

	private String UnicodeToGBK2(String s) {
		String[] k = s.split(";");
		String rs = "";
		for (int i = 0; i < k.length; i++) {
			int strIndex = k[i].indexOf("&#");
			String newstr = k[i];
			if (strIndex > -1) {
				String kstr = "";
				if (strIndex > 0) {
					kstr = newstr.substring(0, strIndex);
					rs += kstr;
					newstr = newstr.substring(strIndex);
				}
				int m = Integer.parseInt(newstr.replace("&#", ""));
				char c = (char) m;
				rs += c;
			} else {
				rs += k[i];
			}
		}
		return rs;
	}

	private String FilterHtml(String str) {
		str = str.replaceAll("<(?!br|img)[^>]+>", "").trim();
		String regEx = "<img src=.*?>";
		Pattern pat = Pattern.compile(regEx);
		Matcher mat = pat.matcher(str);
		
		String regEx1 = "\\[I:[0-9]:.*?\\]";
		Pattern pat1 = Pattern.compile(regEx1);
		
		int nStart = 0;
		int nEnd = 0;
		String strTemp = "";
		while (mat.find()) {
			String strImage = mat.group();
			nStart = mat.start();
			nEnd = mat.end();
			//解析正则表达式的内容			
			if(nStart!=0)		 
				strTemp += str.substring(0,nStart);
			Matcher mat1 = pat1.matcher(strImage);
			if(mat1.find())
			{
				strTemp += mat1.group();
			}
			
			
			str=str.substring(nEnd, str.length());
			mat = pat.matcher(str);
			nStart=0;
			nEnd=0;
		}
		strTemp +=str;
		strTemp = UnicodeToGBK2(strTemp);
		return strTemp;
		//return new String(UNICODE_TO_UTF8(strTemp.getBytes()));
	}
	
	private static final int MASKBITS = 0x3F;
	 private static final int MASKBYTE = 0x80;
	 private static final int MASK2BYTES = 0xC0;
	 private static final int MASK3BYTES = 0xE0;
	 //private static final int MASK4BYTES = 0xF0;
	 //private static final int MASK5BYTES = 0xF8;
	 //private static final int MASK6BYTES = 0xFC;
	/** *//**
	 * @功能: 将UNICODE（UTF-16LE）编码转成UTF-8编码
	 * @参数: byte[] b 源字节数组
	 * @返回值: byte[] b 转为UTF-8编码后的数组
	 * @作者: imuse
	 * @MAIL: postzhu@hotmail.com
	 */
	public static byte[] UNICODE_TO_UTF8(byte[] b)
	{
		int i = 0;
	    int j = 0;
	    byte[] utf8Byte = new byte[b.length * 2];
	    while (i < b.length)
		{
	        byte[] bUTF = new byte[1];
	        int nCode = (b[i] & 0xFF) | ((b[i + 1] & 0xFF) << 8);
	        if (nCode < 0x80)
			{
	            bUTF = new byte[1];
	            bUTF[0] = (byte) nCode;
	        }
	        // 110xxxxx 10xxxxxx
	        else if (nCode < 0x800)
			{
	            bUTF = new byte[2];
	            bUTF[0] = (byte) (MASK2BYTES | nCode >> 6);
	            bUTF[1] = (byte) (MASKBYTE | nCode & MASKBITS);
	        }
	        // 1110xxxx 10xxxxxx 10xxxxxx
	        else if (nCode < 0x10000)
			{
	            bUTF = new byte[3];
	            bUTF[0] = (byte) (MASK3BYTES | nCode >> 12);
	            bUTF[1] = (byte) (MASKBYTE | nCode >> 6 & MASKBITS);
	            bUTF[2] = (byte) (MASKBYTE | nCode & MASKBITS);
	        }
	        for (int k = 0; k < bUTF.length; k++)
			{
	            utf8Byte[j++] = bUTF[k];
	        }
	        i += 2;
	    }
	    b = new byte[j];
	    System.arraycopy(utf8Byte, 0, b, 0, j);
	    return b;
	}
}



